<?php
/**
 * Created by PhpStorm.
 * 售后工单
 * User: ciacm
 * Date: 2017/5/19
 * Time: 13:49
 */

namespace SDXApi\Controller;
use SDXApi\Model\WorkorderModel;
use SDXApi\Service\UserBehavior;
use SDXApi\Service\WorkorderService;
use Common\Api\Ali_ossApi;

class WorkorderController extends AppController {

    /**
     * 获取工单订单列表
     * Created By caicm
     * @param int $uid 用户id
     * @param string $keyword 关键词（商品名称、订单号）模糊搜索
     * @param int $page 分页
     * return mixed
     */
    public function get_order_list(){
        $uid = I('post.uid', 0, 'int');
        $keyword = I('keyword');
        $page = I('post.page', 1, 'int');

        if (empty($uid)) {
            returnApiError('参数有误');
        }

        $workorder_modell = new WorkorderModel();
        $workorder_service = new WorkorderService();
        $workorder_service->uid = $uid;


        if($keyword){
            //添加用户行为
            $user_bevavior = new UserBehavior();
            $user_bevavior->add_browse($uid, 60, 0, $keyword);
        }

        $totle = $workorder_modell->get_order_count($uid, $keyword);
        $pagearr=show_page($totle, $page);
        $order_list = $workorder_service->get_order_list($keyword, $pagearr['firstpage'].','.$pagearr['pagesize']);

        if($page>=$pagearr['pagecount']){
            $data['is_bottom'] = 1;
        }else{
            $data['is_bottom'] = 0;
        }
        $data['count_order'] = $totle;
        $data['order_list'] = $order_list;

        if($order_list){
            returnApiSuccess($data);
        }else{
            returnApiError("无数据！");
        }

    }

    /**
     * 获取工单订单商品列表
     * Created By caicm
     * @param int $uid 用户id
     * @param int $order_id 订单id
     * @param int $page 分页
     * return mixed
     */
    public function get_order_goods_list()
    {
        $uid = I('post.uid', 0, 'int');
        $order_id = I('post.order_id', 0, 'int');
        $page = I('post.page', 1, 'int');

        if (empty($uid) || empty($order_id)) {
            returnApiError('参数有误');
        }

        $workorder_modell = new WorkorderModel();
        $workorder_service = new WorkorderService();
        $workorder_service->uid = $uid;

        $order_info = $workorder_modell->get_order_info($uid, $order_id);
        if(!$order_info){
            returnApiError('订单不存在');
        }
        if($order_info['shipping_status'] !=2 || ($order_info['order_status'] !=1 && $order_info['order_status'] !=5)){
            returnApiError('订单未完成');
        }

        $totle = $workorder_modell->get_order_goods_count($order_id);
        $pagearr=show_page($totle, $page);
        $goods_list = $workorder_service->get_goodslist_by_orderid($order_id, $order_info['confirm_time'] , $pagearr['firstpage'].','.$pagearr['pagesize']);

        if($page>=$pagearr['pagecount']){
            $data['is_bottom'] = 1;
        }else{
            $data['is_bottom'] = 0;
        }
        $data['count_goods'] = $totle;
        $data['order_id'] = $order_info['order_id'];
        $data['order_sn'] = $order_info['order_sn'];
        $data['order_date'] = local_date('Y-m-d H:i', $order_info['add_time']);
        $data['order_time'] = localtotime($order_info['add_time']);
        $data['goods_list'] = $goods_list;

        if($goods_list){
            if($page == 1){
                //添加用户行为
                $user_bevavior = new UserBehavior();
                $user_bevavior->add_browse($uid, 61, $order_info['order_id'], $order_info['order_sn']);
            }

            returnApiSuccess($data);
        }else{
            returnApiError("无数据！");
        }

    }

    /**
     * 获取工单申请信息
     * Created By caicm
     * @param int $uid 用户id
     * @param int $order_id 订单id
     * @param int $goods_id 商品id
     * return mixed
     */
    public function get_apply_workorder_info() {
        $uid = I('post.uid', 0, 'int');
        $order_id = I('post.order_id', 0, 'int');
        $goods_id = I('post.goods_id', 0, 'int');

        if (empty($uid) || empty($order_id) || empty($goods_id)) {
            returnApiError('参数有误');
        }

        $workorder_modell = new WorkorderModel();
        $workorder_service = new WorkorderService();
        $workorder_service->uid = $uid;

        //商品信息
        $goods_info = $workorder_modell->get_order_goods_info($order_id, $goods_id);
        if(!$goods_info){
            returnApiError('信息有误');
        }
        $data['goods_info'] = $goods_info;

        //售后原因
        $cause_list = $workorder_service->get_cause();
        $data['cause_list'] = $cause_list;

        //默认处理方式
        $data['default_dispose_way'] = $cause_list[0]['dispose_way'];

        //售后处理说明
        $data['remark'] = $workorder_service->get_remark();

        if($goods_info){
            //添加用户行为
            $user_bevavior = new UserBehavior();
            $user_bevavior->add_browse($uid, 62, $order_id, $goods_info['goods_name']);
            returnApiSuccess($data);
        }else{
            returnApiError("无数据！");
        }

    }

    /**
     * 工单申请
     * Created By caicm
     * @param int $uid 用户id
     * @param int $order_id 订单id
     * @param int $goods_id 商品id
     * @param int $cause 售后原因（1、商品质量2、商品临期3、漏送4、送错产品5、投诉（投诉没有处理方式）6、其他服务）
     * @param int $dispose_way 处理方式： 1.退款
     * @param string $content 内容
     * @param int $img_id_list 图片id集（多个图片以,号组合）最多4个(可为空)
     * return mixed
     */
    public function apply_workorder(){
        $uid = I('post.uid', 0, 'int');
        $order_id = I('post.order_id', 0, 'int');
        $goods_id = I('post.goods_id', 0, 'int');

        $cause = I('post.cause', 0, 'int');
        $dispose_way = I('post.dispose_way', 0, 'int');
        $content = I('post.content');
        $img_id_list = I("post.img_id_list");

        if (empty($uid) || empty($order_id) || empty($goods_id) || empty($cause) || empty($content)) {
            returnApiError('参数有误');
        }

        $content_len = mb_strlen($content,"utf-8");
        if(10>$content_len || $content_len>300){
            returnApiError('问题描述请输入10~300个字');
        }

        //图片验证
        if($img_id_list){
            $this->check_img($img_id_list, 4);
        }

        //检查处理方式是否有误
        $this->check_dispose_way($cause, $dispose_way);

        $workorder_modell = new WorkorderModel();
        $workorder_service = new WorkorderService();
        $workorder_service->uid = $uid;

        //查询商品是否存在售后记录（排查取消状态）
        $is_workorder = D('Workorder')->get_workorder_count($uid, $order_id, $goods_id);
        if($is_workorder){
            returnApiError('工单已存在不能重复发起');
        }

        //订单信息
        $order_info = $workorder_modell->get_order_info($uid, $order_id);
        if(!$order_info){
            returnApiError('订单不存在');
        }

        //商品信息
        $goods_info = $workorder_modell->get_order_goods_info($order_id, $goods_id);
        if(!$goods_info){
            returnApiError('信息有误');
        }

        //检查商品是否全部退款
        $is_refund = $workorder_service->check_refund($order_id, $goods_id, $goods_info['goods_number']);
        if($is_refund){
            returnApiError('该商品已退款，不能再发起');
        }

        //添加工单
        $workorder_id = $workorder_service->add_workorder($uid, $order_id, $order_info['order_sn'], $goods_id, $goods_info['goods_name'], $cause, $dispose_way, $content, $img_id_list);

        if($workorder_id){
            //添加用户行为
            $user_bevavior = new UserBehavior();
            $user_bevavior->add_browse($uid, 65, $workorder_id, "订单号：{$order_info['order_sn']}，商品名称：{$goods_info['goods_name']}");


            $action_data ['order_id'] = $order_info ['order_id'];
            $action_data ['action_user'] = "buyer";
            $action_data ['order_status'] = $order_info ['order_status'];
            $action_data ['shipping_status'] = $order_info ['shipping_status'];
            $action_data ['pay_status'] = $order_info ['pay_status'];
            $action_data ['action_place'] = 0;
            $action_data ['action_note'] = "【售后原因】【工单{$workorder_id}】".$content;
            $action_data ['log_time'] = gmtime ();
            $action_data ['longitude'] = '';
            $action_data ['latitude'] = '';
            //新增订单操作日志
            D ( 'order_action' )->add ( $action_data );


            returnApiSuccess(array('workorder_id'=>$workorder_id), '操作成功！');
        }else{
            returnApiError("操作失败！");
        }

    }

    /**
     * 补充工单描述
     * Created By caicm
     * @param int $uid 用户id
     * @param int $workorder_id 工单id
     * @param string $content 内容
     * @param int $img_id_list 图片id集（多个图片以,号组合）最多4个(可为空)
     * return mixed
     */
    public function again_apply_workorder(){
        $uid = I('post.uid', 0, 'int');
        $workorder_id = I('post.workorder_id', 0, 'int');

        $content = I('post.content');
        $img_id_list = I("post.img_id_list");

        if (empty($uid) || empty($workorder_id) || empty($content)) {
            returnApiError('参数有误');
        }

        $content_len = mb_strlen($content,"utf-8");
        if(10>$content_len || $content_len>300){
            returnApiError('问题描述请输入10~300个字');
        }

        //图片验证
        if($img_id_list){
            $this->check_img($img_id_list, 4);
        }

        $workorder_modell = new WorkorderModel();
        $workorder_service = new WorkorderService();
        $workorder_service->uid = $uid;

        //售后记录（排查取消状态）
        $workorder_info = $workorder_modell->get_workorder_info($uid, 0, 0, $workorder_id);
        if(!$workorder_info){
            returnApiError('没有工单记录');
        }
        if($workorder_info['status'] == 5){
            returnApiError('工单已关闭，不能发起');
        }

        //添加工单
        $add_workorder = $workorder_service->again_add_workorder($workorder_id,$content, $img_id_list);

        if($add_workorder){
            //添加用户行为
            $user_bevavior = new UserBehavior();
            $user_bevavior->add_browse($uid, 72, $workorder_id, "工单id:{$workorder_id},{$content}");
            returnApiSuccess(array('workorder_id'=>$workorder_id), '操作成功！');
        }else{
            returnApiError("操作失败！");
        }

    }


    /**
     * 获取工单申请记录列表
     * Created By caicm
     * @param int $uid 用户id
     * @param string $keyword 关键词（商品名称、订单号）模糊搜索
     * @param int $page 分页
     * return mixed
     */
    public function workorder_apply_record_list(){
        $uid = I('post.uid', 0, 'int');
        $keyword = I('keyword');
        $page = I('post.page', 1, 'int');

        if (empty($uid)) {
            returnApiError('参数有误');
        }

        $workorder_modell = new WorkorderModel();
        $workorder_service = new WorkorderService();
        $workorder_service->uid = $uid;

        $totle = $workorder_modell->get_workorder_apply_record_count($uid, $keyword);

        $pagearr=show_page($totle, $page);
        $workorder_list = $workorder_service->get_workorder_apply_record($keyword, $pagearr['firstpage'].','.$pagearr['pagesize']);

        if($page>=$pagearr['pagecount']){
            $data['is_bottom'] = 1;
        }else{
            $data['is_bottom'] = 0;
        }
        $data['count_workorder'] = $totle;
        $data['workorder_list'] = $workorder_list;

        if($workorder_list){
            //添加用户行为
            $user_bevavior = new UserBehavior();
            if($page == 1){
                if($keyword){
                    $user_bevavior->add_browse($uid, 67, 0, $keyword);
                }else{
                    $user_bevavior->add_browse($uid, 66);
                }
            }
            returnApiSuccess($data);
        }else{
            returnApiError("无数据！");
        }

    }

    /**
     * 获取售后工单详情
     * Created By caicm
     * @param int $uid 用户id
     * @param int $workorder_id 工单id
     * return mixed
     */
    public function get_workorder_info(){
        $uid = I('post.uid', 0, 'int');
        $workorder_id = I('post.workorder_id', 0, 'int');

        if (empty($uid) || empty($workorder_id)) {
            returnApiError('参数有误');
        }

        $workorder_modell = new WorkorderModel();
        $workorder_service = new WorkorderService();
        $workorder_service->uid = $uid;

        //售后记录（排查取消状态）
        $workorder_info = $workorder_modell->get_workorder_info_by_workorderid($uid, $workorder_id);
        if(!$workorder_info){
            returnApiError('没有工单记录');
        }

        //是否能取消（第一次申请 and 客服未回复）
        $workorder_info['is_cancel'] = 0;
        if($workorder_info['is_reply'] == 0 && $workorder_info['status']==1){
            $workorder_info['is_cancel'] = 1;
        }

        //是否能追加描述(状态不是5/4：关闭/取消的都可以追加)
        $workorder_info['is_superaddition'] = 0;
        if($workorder_info['status'] !=5 && $workorder_info['status'] !=4  ){
            $workorder_info['is_superaddition'] = 1;
        }

        //问题描述
        $workorder_info['content_list'] = $workorder_service->get_content_list($workorder_id);
        $workorder_info['add_date'] = local_date('Y-m-d H:i', $workorder_info['add_time']);
        $workorder_info['add_time'] = localtotime($workorder_info['add_time']);
        $workorder_info['workorder_status'] = $workorder_info['status'];
        $workorder_info['paln_text'] = $workorder_service->get_paln_text($workorder_info['status']);

        unset($workorder_info['is_overlay']);
        unset($workorder_info['cat_id']);
        unset($workorder_info['is_reply']);
        unset($workorder_info['status']);

        //修改工单为已读
        $workorder_modell->update_workorder_is_look($workorder_id);

        if($workorder_info['content_list']){
            //添加用户行为
            $user_bevavior = new UserBehavior();
            $user_bevavior->add_browse($uid, 69, $workorder_id, "工单id:{$workorder_id}");
            returnApiSuccess($workorder_info);
        }else{
            returnApiError("无数据！");
        }

    }

    /**
     * 取消工单
     * Created By caicm
     * @param int $uid 用户id
     * @param int $workorder_id 工单id
     * return mixed
     */
    public function cancel_workorder(){
        $uid = I('post.uid', 0, 'int');
        $workorder_id = I('post.workorder_id', 0, 'int');

        if (empty($uid) || empty($workorder_id)) {
            returnApiError('参数有误');
        }

        $workorder_modell = new WorkorderModel();
        $workorder_service = new WorkorderService();
        $workorder_service->uid = $uid;

        //售后记录
        $workorder_info = $workorder_modell->get_workorder_info_by_workorderid($uid, $workorder_id);


        if(!$workorder_info){
            returnApiError('没有工单记录');
        }

        if($workorder_info['status'] ==4 ){
            returnApiError('当前记录已是取消状态');
        }

        //是否能取消（未处理 and 客服未回复）
        if($workorder_info['is_reply'] != 0 || $workorder_info['status'] !=1 ){
            returnApiError('当前工单不能取消');
        }

        $cancel_workorder = $workorder_service->cancel_workorder($workorder_id);

        if($cancel_workorder){
            //添加用户行为
            $user_bevavior = new UserBehavior();
            $user_bevavior->add_browse($uid, 68, $workorder_id, "工单id:{$workorder_id}");
            returnApiSuccess(null, '操作成功！');
        }else{
            returnApiError("操作失败！");
        }
    }

    /**
     * 售后工单审核进度
     * Created By caicm
     * @param int $uid 用户id
     * @param int $workorder_id 工单id
     * return mixed
     */
    public function workorder_check_plan(){
        $uid = I('post.uid', 0, 'int');
        $workorder_id = I('post.workorder_id', 0, 'int');

        if (empty($uid) || empty($workorder_id)) {
            returnApiError('参数有误');
        }

        $workorder_service = new WorkorderService();
        $workorder_modell = new WorkorderModel();

        //售后记录
        $workorder_info = $workorder_modell->get_workorder_info_by_workorderid($uid, $workorder_id);

        if(!$workorder_info){
            returnApiError('没有工单记录');
        }

        //处理进度状态 1：提交申请，2：客服受理，3：已完成
        $workorder_plan['workorder_status'] = $workorder_service->get_workorder_status($workorder_info['status']);

        //进度内容列表
        $workorder_plan['paln_list'] = $workorder_service->get_paln_list($workorder_id);

        returnApiSuccess($workorder_plan);

    }

    /**
     * 获取退款/售后数量（已提交（客服未处理+已处理未读））
     * Created By caicm
     * @param int $uid
     * return mixed
     */
    public function get_workorder_number(){
        $uid = I('post.uid', 0, 'int');

        if (empty($uid)) {
            returnApiError('参数有误');
        }

        $workorder_modell = new WorkorderModel();

        $workorder_number = $workorder_modell->get_workorder_number($uid);

        returnApiSuccess(array('workorder_number'=>$workorder_number));

    }

    /**
     * 上传售后工单图片
     * Created By caicm
     * @param string img
     * @param int $goods_id 商品id
     * return mixed
     */
    public function upload_img(){
        $img_base64 = I('post.img');
        $goods_id = I('post.goods_id');

        if (empty($img_base64) || empty($goods_id)) {
            returnApiError('参数有误');
        }

        $img_base64 = substr(strstr($img_base64,','),1);
        $img = base64_decode($img_base64);
        $img_name=$goods_id."_".rand(10000000,99999999).".jpg";
        $path= APP_PATH."Runtime/Temp/".$img_name;//接收文件目录
        file_put_contents($path, $img);

        $osspath="data/assets/images/workorder/".$img_name;

        Ali_ossApi::upload($osspath,$path);

        //写入图片表
        $img_id = M('workorder_content_img')->add(array('img_name'=>$osspath,'workorder_content_id'=>0));

        returnApiSuccess(array('img'=>$osspath,'img_id'=>$img_id),'Upload Success');
    }

    /**
     * 文件上传
     */
    public function upload_file(){
        $goods_id = I('post.goods_id');

        if (empty($goods_id)) {
            returnApiError('参数有误');
        }

        if($_FILES['img']['name']){
            $img_name=$goods_id."_".rand(10000000,99999999).".".end(explode('.', $_FILES['img']['name']));
            $path="data/assets/images/workorder/".$img_name;

            Ali_ossApi::upload($path, $_FILES['img']['tmp_name']);
            //写入图片表
            $img_id = M('workorder_content_img')->add(array('img_name'=>$path,'workorder_content_id'=>0));

            returnApiSuccess(array('img'=>$path,'img_id'=>$img_id),'Upload Success');
        }

    }

    /**
     * 上传售后工单图片(批量)
     * Created By caicm
     * @param string img(多个图片以,隔开)
     * @param int $goods_id 商品id
     * return mixed
     */
    public function upload_img_batch(){
        $img = I('post.img');
        $goods_id = I('post.goods_id');

        if (empty($img) || empty($goods_id)) {
            returnApiError('参数有误');
        }

        $list = explode(',',$img);
        $img_list = array();
        foreach ($list as $key=>$val){
            $img_base64 = trim($val);
            if($img_base64){
                $img_base64 = substr(strstr($img_base64,','),1);
                $img = base64_decode($img_base64);
                $img_name=$goods_id."_".rand(10000000,99999999).".jpg";
                $path= APP_PATH."Runtime/Temp/".$img_name;//接收文件目录
                file_put_contents($path, $img);

                $osspath="data/assets/images/workorder/".$img_name;

                Ali_ossApi::upload($osspath,$path);

                //写入图片表
                $img_id = M('workorder_content_img')->add(array('img_name'=>$osspath,'workorder_content_id'=>0));
                $img_list[$key] = array('img'=>$osspath,'img_id'=>$img_id);
            }

        }

        returnApiSuccess(array('img_list'=>$img_list),'Upload Success');
    }


    /**
     * 检查处理方式是否有误
     * Created By caicm
     * @param int $cause 售后原因
     * @param int $dispose_way 处理方式
     * return bool
     */
    protected function check_dispose_way($cause=0, $dispose_way=0){
        $workorder_service = new WorkorderService();
        //售后原因
        $cause_list = $workorder_service->get_cause();
        foreach ($cause_list as $item) {
            if($item['cause_id'] == $cause){
                if($item['dispose_way'] && $dispose_way == 0) {
                    returnApiError('dispose_way参数有误');
                }

                $dispose_way_list = array();
                if(!$item['dispose_way']){
                    $dispose_way_list = array(0);
                }

                foreach ($item['dispose_way'] as $value){
                    $dispose_way_list[] = $value['dispose_id'];
                }
                if(!in_array($dispose_way, $dispose_way_list)){
                    returnApiError('dispose_way参数有误');
                }
            }
        }
    }

    //图片验证
    protected function check_img($img_id_list=0, $num=0){
        $workorder_img_count = M('workorder_content_img')->where(array('img_id'=>array('in',$img_id_list)))->count();

        $img_id_list_count = count(explode(',',$img_id_list));
        if($workorder_img_count != $img_id_list_count){
            returnApiError('img_id_list有误');
        }
        if($img_id_list_count > $num){
            returnApiError("最多{$num}张图片");
        }
    }





}